/**
 * @Description: test
 * @Author: Hu Outstanding
 * @Date: 2022/2/14 18:58
 */
package com.aaa.three.controller;

import com.aaa.three.aop.Log;
import com.aaa.three.pojo.domain.AdminInfo;
import com.aaa.three.pojo.query.AdminInfoQuery;
import com.aaa.three.pojo.vo.AdminVO;
import com.aaa.three.result.AjaxResult;
import com.aaa.three.service.AdminInfoService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("adminsource")

public class AdminSourceController {

    @Autowired
    private AdminInfoService adminInfoService;

    private int a = 0;

    @RequestMapping("download")
    @Log("批量下载员工信息")
    public void download (AdminInfoQuery query, HttpServletResponse response) throws Exception {
        AjaxResult ajaxResult = adminInfoService.queryAdminInfo(query);
        Map data = (Map) ajaxResult.getData();
        List<AdminInfo> currentData = (List<AdminInfo>) data.get("currentData");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("员工信息表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(),AdminInfo.class).sheet("员工信息表").doWrite(currentData);
    }

    @RequestMapping("upload")
    @ResponseBody
    @Log("批量上传员工信息")
    public AjaxResult upload(MultipartFile downloadAdminDemo) throws Exception{

        ExcelReaderBuilder read = EasyExcel.read(  downloadAdminDemo.getInputStream(), AdminVO.class ,null );
        List<AdminVO> objects = read.doReadAllSync();
        for (AdminVO object : objects) {
            Integer q = adminInfoService.addFiles(object);
            if ( q == 1 ){
                a++;
            }
        }
        if (a > 0 ){
            return AjaxResult.success();
        }
        return  AjaxResult.fail("数据添加失败");

    }

}
